from django.contrib import admin

from cloud_disk_app.models import File, Folder

# Register your models here.

admin.site.site_header = admin.site.site_header + ' 网络云盘'


@admin.register(File)
class FileAdmin(admin.ModelAdmin):
    list_display = ['name', 'file', 'folder', 'uploaded_by', 'created_at']

    search_fields = ['name']

    exclude = ['name', 'uploaded_by']

    readonly_fields = ['name']

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "folder":
            kwargs["queryset"] = Folder.objects.filter(user=request.user)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

    def get_queryset(self, request):
        if request.user.is_superuser or request.user.groups.filter(name='云盘应用管理员').exists():
            files = super().get_queryset(request).order_by('-created_at')
        else:
            files = super().get_queryset(request).filter(uploaded_by=request.user).order_by('-created_at')
        return files

    def save_model(self, request, obj, form, change):
        # TODO 将本地文件保存至HDFS

        # 设置文件对象的数据
        obj.name = obj.file.name
        obj.uploaded_by = request.user
        # super().save_model(request, obj, form, change)
        # 保存文件对象数据至数据库
        obj.save()

    def delete_model(self, request, obj):
        # TODO 从HDFS中删除文件

        # 从数据库中删除文件对象数据
        super().delete_model(request, obj)

@admin.register(Folder)
class FolderAdmin(admin.ModelAdmin):
    list_display = ['name', 'parent_folder', 'user']

    exclude = ['user']

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "parent_folder":
            kwargs["queryset"] = Folder.objects.filter(user=request.user)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

    def get_queryset(self, request):
        if request.user.is_superuser or request.user.groups.filter(name='云盘应用管理员').exists():
            folders = super().get_queryset(request)
        else:
            folders = super().get_queryset(request).filter(user=request.user)
        return folders

    def save_model(self, request, obj, form, change):
        # TODO 在HDFS中创建文件夹

        # 设置文件夹对象的数据
        obj.user = request.user
        # super().save_model(request, obj, form, change)
        # 保存文件对象数据至数据库
        obj.save()